package com.mikao.alipay;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.mikao.constant.ErrorCode;
import com.mikao.dao.UserDao;
import com.mikao.util.HttpUtil;
import com.mikao.util.PayCommonUtil;
import com.mikao.util.WXPayUtil;
import com.mikao.wxpay.WxPay;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Created by charlee
 * on 17-9-4
 * version v1.0.0
 */
@CommonsLog
public class AliPay {

    //种植APPID
    private final static String ALIPAY_APPID = "2018091461360472";
    //支付宝私钥
    // private final static String ALIPAY_PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAM/Vh0Me0BhPC37fMgX19SKHIVA0rrSlA+B5S3CsZknod2riMyKY3byAFr9pBX3MuXBYwlF7/pvwNYdWFT9a6pbgD+yu4PMytU7XDOin1t0QTOSNPC/srVLaDAVKape9qLvX1c9WBKxfhMD9CRCzhxINhArG6lW+zTi1FJl+vr75AgMBAAECgYBvfQf2RY0zvRNZl7lp4SsCvqJsOBaP6QVPYUHKy3CDrSSCPZ1YrdAk0kFhpKDBfxTq43I5694FILJWSyNSvR6hoU2mIgO2Xw6ig8274Kw0z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8=";
    //支付宝公钥
    public final static String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhs+fJnlmO5tza/Ur7QUMKR/HkTLURn4xFZ6Cs42S3Sv5S9JccxaPdZUSC27l1GuprnF/7/KULOwFr3qEOSgdhlPb6VSs2Im1kZ4CxhSec3vi5qTPrwj3x30Rbg4ZNmPsY8RtnCAp2/++kOb1kleg4FXQNiml8sgAC3vG0wVmPys5NIPDqCriu0zf3MOrSrd54AaAIlnb8mz2md5G8gV2feYUtQ5DrY6KKFcNEe06BJ30zZfeAS2/riMMAV9Ujss/LR+dxRRkh26QHLwxdAJKvgIEefIav2j3i2DZPEBySduUFzB7gi5TwR727gVFvAHm35klHN4IGKOOlKI983+zWQIDAQAB";

    public final static String ZHIFUBAO_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2wfxIRlw2Sd0o+JeQWmCjRF+p58GwQ6CWMIvmBPGfRwLaofI6W7sAZ90DKjxNXS0N6D0/GJWmxbY8orJ0Q/kg5w13lt1DBa8N3WApTppZtZqGzqtAGN+FoGxqkiPQXeWS7QQzmxEU4OpGZQGhK61hlIlQzm7/A0csW3GV18RS7D6q/7z2RA2mzcXNNJM7Z1EkMvIUuzauHHNyBXIkAfQ8+TPOFMsg+9VIp3FimffKUsaDaug3YWz9MUeYZH3x/DilgeNhpmyYjIX76Z13LKwgaK+9P9vMnidpFqpfUK6SV85GH5K9vasA2DOrgOdkNvt1P6kv3vz3tFnHG2gHVwDKwIDAQAB";
    //服务器支付回调地址
    private final static String NOTIFY_URL = "http://plant.mikao1688.com/plant_api/goods/doAlipayRefound";

    //编码类型
    public final static String CHARSET = "UTF-8";

    private final AlipayClient alipayClient;

    private static UserDao userDao;

    public AliPay() {
        alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", ALIPAY_APPID, ALIPAY_PRIVATE_KEY, "json", CHARSET, ZHIFUBAO_PUBLIC_KEY, "RSA2");
    }

    /**
     * 支付宝生成预支付订单
     *
     * @param out_trade_no 订单号
     * @param subject      订单标题
     * @param body         订单描述
     * @param amount       总价
     * @return 预付款订单字符串 直接返回给APP
     */
    public String aliPay(String out_trade_no, String subject, String body, String amount) {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", ALIPAY_APPID, ALIPAY_PRIVATE_KEY, "json", CHARSET, ZHIFUBAO_PUBLIC_KEY, "RSA2"); //获得初始化的AlipayClient
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request
        alipayRequest.setReturnUrl(NOTIFY_URL);
        alipayRequest.setNotifyUrl(NOTIFY_URL);//在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" + " \"out_trade_no\":\"" + out_trade_no + "\"," + " \"total_amount\":\"" + amount + "\"," + " \"subject\":\"" + subject + "\"," + " \"product_code\":\"QUICK_WAP_PAY\"" + " }");//填充业务参数
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        /*}
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        try {
            httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            httpResponse.getWriter().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            httpResponse.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        /* AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("out_trade_no", out_trade_no);// 订单号
        map.put("total_amount", amount);// 交易金额,单位:元
        map.put("subject", subject);// 订单标题
        map.put("product_code", "QUICK_WAP_PAY");// 销售产品码
        map.put("timeout_express", "90m");// 该笔订单允许的最晚付款时间，逾期将关闭交易
        request.setBizContent(JSON.toJSONString(map));*/
      /*  model.setOutTradeNo(out_trade_no);
        model.setSubject(subject);
        model.setBody(body);
        model.setTotalAmount(amount);
        model.setProductCode("QUICK_WAP_PAY");
        model.setTimeoutExpress("90m");
        request.setBizModel(model);*/
        /*httpResponse.setContentType("text/html;charset=" + CHARSET);
        try {
            httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            httpResponse.getWriter().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            httpResponse.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        return form;
    }

    /**
     * 支付宝退款
     *
     * @param out_trade_no  交易订单号
     * @param refund_amount 退款金额
     * @param refund_reason 退款理由
     * @return 是否成功
     */
    public AlipayTradeRefundResponse refund(String out_trade_no, String refund_amount, String refund_reason) {
        AlipayTradeRefundRequest refundRequest = new AlipayTradeRefundRequest();
        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
        model.setOutTradeNo(out_trade_no);
        model.setRefundAmount(refund_amount);
        model.setRefundReason(refund_reason);
        refundRequest.setBizModel(model);
        try {
            return alipayClient.execute(refundRequest);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {

        AliPay aliPay = new AliPay();

        AlipayTradeRefundResponse refund = aliPay.refund("20180921094514", "1.00", "测试退款");



    }
}
